package com.pdool.game.core.msg;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Parser;
import com.pdool.common.constants.Constant;
import com.pdool.common.constants.ErrorCode;
import com.pdool.common.constants.MsgId;
import com.pdool.common.dto.room.ClientRoomMsg;
import com.pdool.common.exception.ErrorException;
import com.pdool.common.msg.common.ErrorMsgResp;
import com.pdool.game.logic.mgr.MatchMgr;
import com.pdool.game.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;

import java.nio.ByteBuffer;

/**
 * 消息任务
 */
@Slf4j
public class MsgTask implements Runnable {
    WebSocketSession session;
    BinaryMessage message;

    Long roleId;

    public MsgTask(WebSocketSession session, BinaryMessage message, Long roleId) {
        this.session = session;
        this.message = message;
        this.roleId = roleId;
    }

    @Override
    public void run() {
        try {
            ByteBuffer payload = message.getPayload();
            int msgId = payload.getInt();
            byte[] dst = new byte[payload.remaining()];
            payload.get(dst);
            if (msgId > Constant.ROOM_MSG_GAP) {
                String roomId = MatchMgr.getInstance().getRoleRoomMap().get(roleId);
                if (roomId != null){
                    ClientRoomMsg clientRoomMsg = new ClientRoomMsg();
                    clientRoomMsg.setMsgId(msgId);
                    clientRoomMsg.setRoleId(roleId);
                    clientRoomMsg.setMsg(dst);
                    RoomRemoteMgr.getInstance().getRoomService().trans2Room(roomId, clientRoomMsg);
                }
                return;
            }
            MsgHandlerItem msgHandlerItem = MsgMgr.getHandlerMap().get(msgId);
            Parser<?> in = msgHandlerItem.getIn();
            IHandler handler = msgHandlerItem.getHandler();

            GeneratedMessageV3 inMsg = (GeneratedMessageV3) in.parseFrom(dst);
            GeneratedMessageV3 result = handler.handle(roleId, inMsg);
            if (result != null) {
                SessionUtil.pushMsg(session, msgId, result);
            }
        } catch (ErrorException e) {
            log.error("", e);
            String errorMsg = e.getMessage();
            String errorCode = e.getErrorCode();

            ErrorMsgResp build = ErrorMsgResp.newBuilder().setErrCode(errorCode).setMsg(errorMsg).build();
            SessionUtil.pushMsg(session, MsgId.ERROR, build);
        } catch (Exception e) {
            log.error("", e);
            ErrorMsgResp build = ErrorMsgResp.newBuilder().setErrCode(ErrorCode.UNKNOWN_ERROR).build();
            SessionUtil.pushMsg(session, MsgId.ERROR, build);
        }
    }
}
